const App = {
  mixins: [Save], //配置文件，路径/utils/mixins.js
  data() {
    return {
      originalTableData2: [],
      selectedCount: 0,
      filterText: "",
      treeData: [],
      checkboxOptions2: [],
      // 复选框选项数组
      checkboxOptions: [],
      // 选中的选项值数组
      selectedOptions: [],

      childDataForm: [{}],
      tableData: [],

      dialogFormVisible: false,
      Village_Number: "",
      patrol_team_SerialNumber: "",
      dialogVisible: false,
      currentMember: {}
    };
  },
  mounted() {
    let ls_URL = window.location.href;
    this.patrol_team_SerialNumber = getQueryObject(ls_URL, "nodeKey");
    this.Village_Number = getQueryObject(ls_URL, "Village_Number");

    this.Getparty_memberAndSetData(this.patrol_team_SerialNumber);

    this.Setparty_organizationTree();

  },
  watch: {
    filterText(newVal) {
      if (this.$refs.tree) {
        this.$refs.tree.filter(newVal);
      }
    },
  },
  methods: {
    handleNameClick(row) {
      $.ajax({
        headers: requestHeaders(),

        url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
        method: "POST",
        data: {
          Data: 'personal_information', //sql名
          Condition: "Row_Status='0' and ID_Card_Number='" + row.ID_Card_Number + "'"
        },
        success: (res) => {
          this.currentMember = { ...res[0] };
          this.dialogVisible = true;

        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
      });


    },
    handleSelect(row) {

      this.tableData.forEach(item => {
        item.Is_Captain = '0'
      })
      row.Is_Captain = '1'
      // console.log('当前选中行:', row);
    },

    cren(Arg_res) {
      const _this = this;


      $.ajax({
        headers: requestHeaders(),

        url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
        method: "POST",
        data: {
          Data: 'patrol_member', //sql名
          Condition: "Row_Status='0' and Team_SerialNumber='" + Arg_res + "'"
        },
        success: (res) => {
          console.log("接口返回数据:", res);

          if (res.length > 0) {


            let _res = res.map(item => {
              let _checkboxOptions2 = _this.checkboxOptions2.filter(personal => personal.ID_Card_Number == item.ID_Card_Number)
              return {
                Personal_Name: _checkboxOptions2[0].Personal_Name,
                Contact_Phone: _checkboxOptions2[0].Contact_Phone,
                ...item
              }
            })
            _this.tableData = _res.map(i => deepClone(i));
            _this.originalTableData2 = _res.map(i => deepClone(i));
            _this.checkboxOptions = _res.map(i => deepClone(i));



            console.log("_this.tableData", _this.tableData);

            // _this.checkboxOptions = res;
            _this.setCheckboxesSelected(_res);; // 恢复选中状态

          }
          else {


          }
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
      });


    },

    // 设置复选框选中状态的方法
    setCheckboxesSelected(selectedMembers) {
      console.log(
        "设置复选框选中状态，已选中成员数量:",
        selectedMembers.length
      );

      const selectedIds = selectedMembers.map(
        (member) => member.ID_Card_Number
      );
      // const captainId = this.childDataForm[0]?.ID_Card_Number;
      const selectedIdMap = new Map(selectedIds.map(id => [id, true]));

      this.checkboxOptions.forEach(option => {
        // if (option.ID_Card_Number === captainId) {
        //   option.checked = false;
        //   return;
        // }

        const isSelected = selectedIdMap.has(option.ID_Card_Number);
        option.checked = isSelected;
        console.log(`成员 ${option.Personal_Name} 选中状态:`, isSelected);
      });



      this.updateSelectedCount();
      this.handleCheckboxChange();
      console.log("设置完成，当前已选数量:", this.selectedCount);
    },

    handleCheckboxChange(option) {

      let _this = this;
      const selectedMembers = _this.checkboxOptions.filter(
        (option) =>
          option.checked
      );
      console.log("watch1", this.tableData)

      this.tableData = selectedMembers.map((option) => {
        const original = this.originalTableData2.find(
          (item) => item.ID_Card_Number === option.ID_Card_Number
        );

        //​覆盖策略​：默认行为（无需额外处理）
        return {
          ...original,  //将 option 对象的所有可枚举属性浅拷贝到新对象中，作为基础属性
          Contact_Phone: original?.Mobile || option.Contact_Phone || "", // 确保使用option对象优先使用 original.Mobile，若不存在则回退到 option.Contact_Phone，最后保底为空字符串
          Position: original?.Position || "",
          Start_Date: original?.Start_Date || "",
          Personal_Name: option?.Personal_Name || "",
          ID_Card_Number: option?.ID_Card_Number || ""

        };
      });
      console.log("watch2", this.tableData)

      this.updateSelectedCount();
    },


    // 清空选中并移除选项
    clearAll() {

      // 没有负责人时，清空列表
      this.checkboxOptions = [];

      this.handleCheckboxChange()
      // 更新已选数量
      this.updateSelectedCount();
    },
    // 更新已选数量
    updateSelectedCount() {
      this.selectedCount = this.checkboxOptions.filter(
        (option) => option.checked
      ).length;
    },

    handleNodeClick(data) {
      const _this = this;
      _this.checkboxOptions = _this.checkboxOptions.filter(item => item.checked)
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryBySQLSerialNumber`,
        type: "post",
        data: {
          SQLSerialNumber: "SQL_personal_information_Query",
          Condition: "",
          ExtensionCondition: window.btoa(
            unescape(
              encodeURIComponent(
                "AND personal_information.RR_Village_Number='" +
                data.ProvinceNumber + "'"
              )
            )
          ),
        },
        success: (newMembers) => {
          console.log("获取到新的人员列表:", newMembers);


          // 创建一个映射，用于快速查找已存在的人员
          const existingMap = {};
          _this.checkboxOptions.forEach((member) => {
            existingMap[member.ID_Card_Number] = member;
          });

          // 合并新的人员列表到现有列表，排除当前负责人
          newMembers.forEach((newMember) => {


            // 如果人员已存在，保留其选中状态
            if (existingMap[newMember.ID_Card_Number]) {
              Object.assign(existingMap[newMember.ID_Card_Number], newMember);
            } else {
              // 添加新人员，并默认设置为未选中
              _this.checkboxOptions.push({
                ...newMember,
                checked: false,
              });
            }
          });

          // 更新已选数量
          _this.updateSelectedCount();

          console.log("合并后的人员列表:", _this.checkboxOptions);
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },




    Setparty_organizationTree() {
      const _this = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/permissionsTree/getDistrictTreeByPermissions`,
        type: "GET",
        data: {
          DistrictCode: getCookie('village'),
        },
        success: (data) => {


          _this.treeData = data.map((item) => ({
            id: item.ProvinceNumber, // 假设原始数据中的code字段对应树组件的id
            label: item.Province, // 假设原始数据中的name字段对应树组件的label
            // 保留其他可能需要的字段
            ...item,
          }));

        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },

    handleSubmit2() {
      let _this = this;

      console.log("提交前", _this.tableData)

      console.log("提交前原值", _this.originalTableData2)



      //比对tableData内的记录与originalTableData2记录的差异,
      // 如果tableData不包含originalTableData2则插入tableData一条带原值的Row_status=1的记录,代表删除
      const ltableData = _this.originalTableData2.map(option => {
        // const original = _this.tableData.find(
        //   item => item.ID_Card_Number === option.ID_Card_Number
        // );

        const bhas = _this.tableData.some(
          item => item.ID_Card_Number === option.ID_Card_Number
        );

        // ​覆盖策略​：默认行为（无需额外处理）
        // ​合并值​：若需保留所有值，可将重复键的值合并为数组：

        if (!bhas) {
          return {
            ...option,  //将 option 对象的所有可枚举属性浅拷贝到新对象中，作为基础属性

            Row_Status: "1"

          };
        }

      });
      //将undefined的条目清理
      const cleaned = ltableData.filter(item => item !== undefined);

      if (cleaned.length > 0) {
        _this.tableData.push(...cleaned);
      }

      console.log("处理完Row_Status", _this.tableData)

      //调用 通用的提交方法
      _this.handleSubmit();
    },


    Getparty_memberAndSetData(Arg_res) {
      const _this = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryBySQLSerialNumber`,
        method: "post",
        data: {
          SQLSerialNumber: "SQL_personal_information_Query", //sql名
          Condition: "", //不必选的条件
          // ExtensionCondition: window.btoa(unescape(encodeURIComponent(" and RR_Village_Number in (" + getCookie('village') + ")"))), //不必选的扩展sql
          ExtensionCondition: ""
        },
        success: (res) => {
          console.log(res);
          _this.checkboxOptions2 = res;
          _this.cren(Arg_res);
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
      });
    },

    xin() {
      const _this = this;
      _this.checkboxOptions = _this.checkboxOptions.filter(item => item.checked)
      this.dialogFormVisible = true;
    },
  },
};

const { createApp, ref } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}
const ElMessage = ElementPlus.ElMessage;
app.mount("#app");
